package main

import (
	"context"
	"errors"
	"gitee.com/zxs-micro-2/zxs-micro-proto/demouser/user"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"math/rand"
	"net"
	"time"
)

type UserServer struct {
	user.UnimplementedDemoUserServer
}

type UserData struct {
	UserName  string `json:"user_name"`
	LoginTime string `json:"login_time"`
}

//账号-密码对应
var users map[string]string

//token-用户信息对应
var loginUsers map[string]*UserData
var r *rand.Rand

var logger *zap.Logger

func init() {
	users = make(map[string]string)
	loginUsers = make(map[string]*UserData)
	r = rand.New(rand.NewSource(time.Now().Unix()))
	logger, _ = zap.NewProduction()
}

func main() {
	lst, _ := net.Listen("tcp", "127.0.0.1:8124")
	s := grpc.NewServer()
	server := new(UserServer)
	user.RegisterDemoUserServer(s, server)
	defer lst.Close()
	s.Serve(lst)
}

func (u UserServer) UserRegister(ctx context.Context, request *user.UserRegisterRequest) (
	*user.UserRegisterResponse, error) {
	name := request.Account
	if request.RegisterCode == "" || request.Pwd != request.VerifyPwd {
		logger.Error("参数错误")
		return nil, errors.New("参数错误")
	}
	_, ok := users[name]
	if ok {
		logger.Error("账号已存在")
		return nil, errors.New("账号已存在")
	}
	users[name] = request.Pwd
	return &user.UserRegisterResponse{
		Types: "success",
	}, nil
}

func (u UserServer) UserLogin(ctx context.Context, request *user.UserLoginRequest) (
	*user.UserLoginResponse, error) {
	userPwd, ok := users[request.Account]
	if !ok {
		logger.Error("账号不存在")
		return nil, errors.New("账号不存在")
	}
	if userPwd != request.Pwd {
		logger.Error("账号/密码错误")
		return nil, errors.New("账号/密码错误")
	}
	ud := &UserData{
		UserName:  request.Account,
		LoginTime: time.Now().String(),
	}
	token := RandString(16)
	loginUsers[token] = ud
	return &user.UserLoginResponse{
		Token: token,
	}, nil
}

func (u UserServer) UserInfo(ctx context.Context, request *user.UserInfoRequest) (
	*user.UserInfoResponse, error) {
	ud, ok := loginUsers[request.Token]
	if !ok {
		logger.Error("账号未登录")
		return nil, errors.New("账号未登录")
	}
	return &user.UserInfoResponse{
		Account: ud.UserName, LoginTime: ud.LoginTime,
	}, nil
}

func (u UserServer) mustEmbedUnimplementedDemoUserServer() {
	//TODO implement me
	panic("implement me")
}

func RandString(len int) string {
	bytes := make([]byte, len)
	for i := 0; i < len; i++ {
		b := r.Intn(26) + 65
		bytes[i] = byte(b)
	}
	return string(bytes)
}
